package main

import (
	stdLog "log"
	"syscall"

	"github.com/fvbock/endless"
	"github.com/gin-gonic/gin"
	flag "github.com/spf13/pflag"
	_ "github.com/super-team/start-kit/api"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"

	"github.com/super-team/start-kit/configs"
	"github.com/super-team/start-kit/handler"
	"github.com/super-team/start-kit/middlewares"
	"github.com/super-team/start-kit/pkg/casbin"
	"github.com/super-team/start-kit/pkg/mysql"
	"github.com/super-team/start-kit/tools/log"
)

func init() {
	var configPath = flag.String("config", "./configs", "请输入配置文件路径")
	flag.Parse()
	configs.InitConfig(*configPath)
	log.InitLogger()
	mysql.InitMysql()
	casbin.InitCasBin()
}

// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/

// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email support@swagger.io

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host petstore.swagger.io
// @BasePath /api
func main() {
	if configs.Config.Server.Debug {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	r := gin.New()

	middleware.RegisterMiddleware(r)
	handler.RegisterRoutes(r)

	//swagger
	r.GET("/swagger/*any", ginSwagger.DisablingWrapHandler(swaggerFiles.Handler, "NO_SWAGGER"))

	server := endless.NewServer(configs.Config.Server.Addr, r)
	server.SignalHooks[endless.POST_SIGNAL][syscall.SIGUSR1] = append(
		server.SignalHooks[endless.POST_SIGNAL][syscall.SIGUSR1], closeServiceAfterShutdown)
	server.SignalHooks[endless.POST_SIGNAL][syscall.SIGINT] = append(
		server.SignalHooks[endless.POST_SIGNAL][syscall.SIGINT], closeServiceAfterShutdown)
	if err := server.ListenAndServe(); err != nil {
		stdLog.Fatalln(err.Error())
	}
}

/**
服务器关闭，关闭对应服务
*/
func closeServiceAfterShutdown() {
	mysql.Close()
}
